package app

import (
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/boticord/backend/notifications/types"
	"go.uber.org/fx"
	"io"
	"net/http"
)

func newRpc() fx.Option {
	return fx.Module("rpc", fx.Provide(func(config *Config) *RPC {
		return &RPC{key: config.RpcSecret, port: config.AppPort}
	}))
}

type RPC struct {
	key  string
	port string
}

func formatServiceName(name, port string) string {
	return fmt.Sprintf("%s-service:%s", name, port)
}

func RpcCall[Resp any, Req any](r *RPC, service, method, function string, req Req) (*Resp, error) {
	v, _ := json.Marshal(req)
	host := formatServiceName(service, r.port)
	var response types.Response[Resp]
	reqst, _ := http.NewRequest(method, fmt.Sprintf("http://%s/rpc/%s/", host, function), bytes.NewBuffer(v))
	reqst.Header.Set("X-Boticord-Rpc", r.key)
	reqst.Header.Set("Content-Type", "application/json")
	resp, err := http.DefaultClient.Do(reqst)
	if err != nil {
		return nil, err
	}
	b, _ := io.ReadAll(resp.Body)
	json.Unmarshal(b, &response)

	if !response.Ok {
		return nil, response.Errors
	} else {
		return response.Result, nil
	}
}
